package org.example.http;

import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lilei
 * @date 2020-04-06
 */
@Data
public class BRequest {
    private String method;
    private String url;
    private Map<String, Object> parameters = new HashMap<>();
    private InputStream in;

    public BRequest(InputStream in) {
        this.in = in;
        init();
    }

    private void init() {
        String content = "";
        byte[] buff = new byte[1024];
        int len = 0;
        try {
            if ((len = in.read(buff)) != -1) {
                content = new String(buff);
            }

            if (!"".equals(content)) {
                String[] requestHead = content.split(" ");
                this.setMethod(requestHead[0]);
                String[] requestUrl = requestHead[1].split("\\?");
                this.setUrl(requestUrl[0]);
                if (requestUrl.length > 1) {
                    String[] requestParameters = requestUrl[1].split("&");
                    for (String requestParameter : requestParameters) {
                        String[] inx = requestParameter.split("=");
                        parameters.put(inx[0], inx[1]);
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
